<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="${course.title} + ' - 课程详情'">课程详情</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        :root {
            --primary: #4a6bff;
            --secondary: #6c757d;
            --success: #28a745;
            --warning: #ffc107;
            --danger: #dc3545;
            --light: #f8f9fa;
            --dark: #343a40;
            --border-radius: 8px;
            --box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            --transition: all 0.3s ease;
        }

        body {
            background-color: #f5f7fb;
            color: #333;
            line-height: 1.6;
        }

        .container {
            display: flex;
            min-height: 100vh;
        }

        /* 侧边栏样式 */
        .sidebar {
            width: 300px;
            background-color: white;
            padding: 20px 0;
            box-shadow: var(--box-shadow);
            z-index: 100;
            overflow-y: auto;
        }

        .course-header {
            padding: 0 20px 20px;
            border-bottom: 1px solid #eaeaea;
            margin-bottom: 20px;
        }

        .back-btn {
            display: flex;
            align-items: center;
            color: var(--primary);
            text-decoration: none;
            margin-bottom: 15px;
            font-weight: 500;
        }

        .back-btn i {
            margin-right: 8px;
        }

        .course-title {
            font-size: 22px;
            margin-bottom: 5px;
            color: var(--dark);
        }

        .course-instructor {
            color: var(--secondary);
            font-size: 14px;
        }

        .progress-container {
            margin-top: 15px;
        }

        .progress-info {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
            font-size: 14px;
        }

        .progress-bar {
            height: 8px;
            background-color: #e9ecef;
            border-radius: 4px;
            overflow: hidden;
        }

        .progress {
            height: 100%;
            background-color: var(--success);
            border-radius: 4px;
            width: 65%; /* 初始进度 */
        }

        .chapters-list {
            list-style: none;
            padding: 0 10px;
        }

        .chapter-item {
            padding: 12px 15px;
            margin: 5px 0;
            border-radius: var(--border-radius);
            cursor: pointer;
            transition: var(--transition);
            display: flex;
            align-items: center;
            border: 1px solid transparent;
        }

        .chapter-item.active {
            background-color: rgba(74, 107, 255, 0.1);
            border-color: var(--primary);
        }

        .chapter-item:hover {
            background-color: rgba(74, 107, 255, 0.05);
        }

        .chapter-number {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background-color: #e9ecef;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 12px;
            font-weight: 500;
            font-size: 14px;
            transition: var(--transition);
        }

        .chapter-item.active .chapter-number {
            background-color: var(--primary);
            color: white;
        }

        .chapter-item.completed .chapter-number {
            background-color: var(--success);
            color: white;
        }

        .chapter-content {
            flex: 1;
        }

        .chapter-title {
            font-weight: 500;
            margin-bottom: 3px;
        }

        .chapter-duration {
            font-size: 12px;
            color: var(--secondary);
        }

        .chapter-status {
            margin-left: 10px;
        }

        .status-badge {
            padding: 4px 8px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
        }

        .status-completed {
            background-color: #e8f5e9;
            color: var(--success);
        }

        .status-pending {
            background-color: #fff3e0;
            color: #ff9800;
        }

        /* 主内容区样式 */
        .main-content {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
        }

        .content-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eaeaea;
        }

        .chapter-nav {
            display: flex;
            gap: 10px;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 500;
            transition: var(--transition);
            display: flex;
            align-items: center;
        }

        .btn i {
            margin-right: 5px;
        }

        .btn-outline {
            background-color: transparent;
            border: 1px solid var(--primary);
            color: var(--primary);
        }

        .btn-outline:hover {
            background-color: var(--primary);
            color: white;
        }

        .btn-primary {
            background-color: var(--primary);
            color: white;
        }

        .btn-primary:hover {
            background-color: #3a5bd9;
        }

        .btn-success {
            background-color: var(--success);
            color: white;
        }

        .btn-success:hover {
            background-color: #218838;
        }

        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .content-body {
            background-color: white;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            padding: 25px;
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .chapter-title-large {
            font-size: 24px;
            margin-bottom: 10px;
            color: var(--dark);
        }

        .chapter-meta {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
            color: var(--secondary);
            font-size: 14px;
        }

        .material-container {
            flex: 1;
            border: 1px solid #eaeaea;
            border-radius: var(--border-radius);
            padding: 20px;
            margin-bottom: 20px;
            background-color: #f9f9f9;
        }

        .material-section {
            margin-bottom: 30px;
            background: white;
            border-radius: var(--border-radius);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
            overflow: hidden;
        }

        .material-header {
            display: flex;
            align-items: center;
            padding: 15px 20px;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-bottom: 1px solid #dee2e6;
        }

        .pdf-container {
            width: 100%;
            height: 600px;
            border: 1px solid #ddd;
            border-radius: 5px;
            overflow: hidden;
            background: white;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .image-container {
            text-align: center;
            padding: 20px;
            background: white;
            border-radius: 5px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }

        .text-container {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 5px;
            border-left: 4px solid var(--primary);
        }

        .file-info {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 5px;
            text-align: center;
        }

        .material-content h3 {
            margin: 20px 0 10px;
            color: var(--primary);
        }

        .material-content p {
            margin-bottom: 15px;
        }

        .material-content ul, .material-content ol {
            margin-left: 20px;
            margin-bottom: 15px;
        }

        .material-content li {
            margin-bottom: 8px;
        }

        .action-buttons {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .completion-status {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                flex-direction: column;
            }

            .sidebar {
                width: 100%;
                max-height: 300px;
            }

            .content-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
            }

            .chapter-nav {
                width: 100%;
                justify-content: space-between;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <!-- 侧边栏 - 章节列表 -->
    <div class="sidebar">
        <div class="course-header">
            <a href="/student/home" class="back-btn">
                <i class="fas fa-arrow-left"></i>
                返回课程列表
            </a>
            <h2 class="course-title" th:text="${course.title}">课程名称</h2>
            <p class="course-instructor">教师</p>

            <div class="progress-container">
                <div class="progress-info">
                    <span>课程进度</span>
                    <span id="progress-percentage">0%</span>
                </div>
                <div class="progress-bar">
                    <div class="progress" id="progress-bar"></div>
                </div>
            </div>
        </div>

        <ul class="chapters-list" id="chapters-list">
            <li th:each="chapter, iterStat : ${chapters}" 
                th:class="'chapter-item' + (${iterStat.first} ? ' active' : '')" 
                th:data-chapter="${chapter.id}">
                <div class="chapter-number" th:text="${iterStat.count}">1</div>
                <div class="chapter-content">
                    <div class="chapter-title" th:text="${chapter.title}">章节标题</div>
                    <div class="chapter-duration">章节内容</div>
                </div>
                <div class="chapter-status">
                    <span class="status-badge status-pending">未开始</span>
                </div>
            </li>
        </ul>
    </div>

    <!-- 主内容区 - 课件展示 -->
    <div class="main-content">
        <div class="content-header">
            <div>
                <h2 id="current-chapter-title">请选择章节</h2>
                <p class="chapter-meta">
                    <span><i class="far fa-clock"></i> 预计学习时间: <span id="chapter-duration">-</span></span>
                    <span><i class="far fa-file-alt"></i> 课件: <span id="material-count">0</span>个</span>
                </p>
            </div>

            <div class="chapter-nav">
                <button class="btn btn-outline" id="prev-chapter">
                    <i class="fas fa-chevron-left"></i> 上一章
                </button>
                <button class="btn btn-outline" id="next-chapter">
                    下一章 <i class="fas fa-chevron-right"></i>
                </button>
            </div>
        </div>

        <div class="content-body">
            <h3 class="chapter-title-large" id="chapter-title-large">请选择章节开始学习</h3>

            <!-- 课件内容显示区域 -->
            <div class="material-container" id="material-container">
                <div id="material-content">
                    <p>请从左侧选择章节查看课件内容</p>
                </div>
            </div>

            <div class="action-buttons">
                <div class="completion-status">
                    <i class="fas fa-check-circle" style="color: #28a745;"></i>
                    <span>完成本章节以继续学习</span>
                </div>
                <button class="btn btn-success" id="complete-chapter">
                    <i class="fas fa-check"></i> 标记为已完成
                </button>
            </div>
        </div>
    </div>
</div>

<script th:inline="javascript">
    document.addEventListener('DOMContentLoaded', function() {
        // 从服务器获取数据
        const chapters = /*[[${chapters}]]*/ [];
        const chapterMaterials = /*[[${chapterMaterials}]]*/ {};
        const course = /*[[${course}]]*/ {};
        
        const chapterItems = document.querySelectorAll('.chapter-item');
        const prevBtn = document.getElementById('prev-chapter');
        const nextBtn = document.getElementById('next-chapter');
        const completeBtn = document.getElementById('complete-chapter');

        let currentChapter = null; // 当前章节ID

        // 页面加载时检查章节完成状态
        loadChapterCompletions();

        // 加载章节完成状态
        function loadChapterCompletions() {
            if (!course.id) return;
            
            fetch(`/student/course/${course.id}/completions`)
                .then(response => response.json())
                .then(completions => {
                    // 标记已完成的章节
                    completions.forEach(completion => {
                        const chapterItem = document.querySelector(`.chapter-item[data-chapter="${completion.chapter_id}"]`);
                        if (chapterItem) {
                            chapterItem.classList.add('completed');
                            chapterItem.querySelector('.chapter-number').classList.add('completed');
                            chapterItem.querySelector('.status-badge').textContent = '已完成';
                            chapterItem.querySelector('.status-badge').className = 'status-badge status-completed';
                        }
                    });
                    
                    // 更新进度条
                    updateProgress();
                })
                .catch(error => {
                    console.error('加载章节完成状态失败:', error);
                });
        }

        // 更新章节导航按钮状态
        function updateNavButtons() {
            if (currentChapter === null) {
                prevBtn.disabled = true;
                nextBtn.disabled = true;
                return;
            }
            
            const currentIndex = chapters.findIndex(ch => ch.id === currentChapter);
            prevBtn.disabled = currentIndex <= 0;
            nextBtn.disabled = currentIndex >= chapters.length - 1;
        }

        // 切换章节
        function switchChapter(chapterId) {
            currentChapter = chapterId;

            // 更新章节列表中的活跃状态
            chapterItems.forEach(item => {
                item.classList.remove('active');
                if (parseInt(item.getAttribute('data-chapter')) === chapterId) {
                    item.classList.add('active');
                }
            });

            // 更新内容区域
            updateChapterContent(chapterId);

            // 更新导航按钮状态
            updateNavButtons();

            // 检查当前章节的完成状态
            checkChapterCompletionStatus(chapterId);
        }

        // 检查章节完成状态
        function checkChapterCompletionStatus(chapterId) {
            fetch(`/student/chapter/${chapterId}/completion`)
                .then(response => response.json())
                .then(data => {
                    const isCompleted = data.completed === true;
                    const currentItem = document.querySelector(`.chapter-item[data-chapter="${chapterId}"]`);
                    
                    // 更新章节列表中的完成状态
                    if (currentItem) {
                        if (isCompleted) {
                            currentItem.classList.add('completed');
                            currentItem.querySelector('.chapter-number').classList.add('completed');
                            currentItem.querySelector('.status-badge').textContent = '已完成';
                            currentItem.querySelector('.status-badge').className = 'status-badge status-completed';
                        } else {
                            currentItem.classList.remove('completed');
                            currentItem.querySelector('.chapter-number').classList.remove('completed');
                            currentItem.querySelector('.status-badge').textContent = '未完成';
                            currentItem.querySelector('.status-badge').className = 'status-badge';
                        }
                    }
                    
                    // 更新完成按钮状态
                    completeBtn.disabled = isCompleted;
                    completeBtn.innerHTML = isCompleted ?
                        '<i class="fas fa-check"></i> 已完成' :
                        '<i class="fas fa-check"></i> 标记为已完成';
                    completeBtn.style.backgroundColor = isCompleted ? '#6c757d' : '#28a745';
                    
                    // 更新进度条
                    updateProgress();
                })
                .catch(error => {
                    console.error('检查章节完成状态失败:', error);
                    // 如果检查失败，使用DOM状态作为备选
                    const currentItem = document.querySelector(`.chapter-item[data-chapter="${chapterId}"]`);
                    const isCompleted = currentItem ? currentItem.classList.contains('completed') : false;
                    completeBtn.disabled = isCompleted;
                    completeBtn.innerHTML = isCompleted ?
                        '<i class="fas fa-check"></i> 已完成' :
                        '<i class="fas fa-check"></i> 标记为已完成';
                    completeBtn.style.backgroundColor = isCompleted ? '#6c757d' : '#28a745';
                });
        }

        // 更新章节内容
        function updateChapterContent(chapterId) {
            const chapter = chapters.find(ch => ch.id === chapterId);
            if (!chapter) return;

            // 更新标题
            document.getElementById('current-chapter-title').textContent = chapter.title;
            document.getElementById('chapter-title-large').textContent = chapter.title;

            // 更新课件信息
            const materials = chapterMaterials[chapterId] || [];
            document.getElementById('material-count').textContent = materials.length;
            document.getElementById('chapter-duration').textContent = '30分钟'; // 默认时间

            // 更新课件内容
            updateMaterialContent(materials);
        }

        // 更新课件内容
        function updateMaterialContent(materials) {
            const materialContent = document.getElementById('material-content');
            
            if (materials.length === 0) {
                materialContent.innerHTML = '<p>该章节暂无课件</p>';
                return;
            }

            let html = '';
            materials.forEach((material, index) => {
                const fileIcon = getFileIcon(material.contentType || material.name);
                const isPdf = (material.url && material.url.includes('pdf')) || 
                             (material.name && material.name.toLowerCase().endsWith('.pdf'));
                
                // 课件标题
                html += `
                    <div class="material-section" style="margin-bottom: 30px;">
                        <div class="material-header" style="display: flex; align-items: center; margin-bottom: 15px; padding-bottom: 10px; border-bottom: 2px solid var(--primary);">
                            <i class="fas ${fileIcon}" style="margin-right: 10px; color: var(--primary); font-size: 20px;"></i>
                            <h4 style="margin: 0; color: var(--dark);">${material.name}</h4>
                        </div>
                `;
                
                // 根据文件类型显示不同内容
                if (isPdf) {
                    // PDF文件直接嵌入显示
                    const pdfUrl = `/uploads/${material.url}`;
                    html += `
                        <div class="pdf-container" style="width: 100%; height: 600px; border: 1px solid #ddd; border-radius: 5px; overflow: hidden; background: white;">
                            <iframe src="${pdfUrl}" 
                                    style="width: 100%; height: 100%; border: none;" 
                                    title="${material.name}"
                                    onload="console.log('PDF loaded:', '${material.name}')"
                                    onerror="console.error('PDF load error:', '${material.name}')">
                            </iframe>
                        </div>
                    `;
                } else if (material.url && material.url.includes('image')) {
                    // 图片文件直接显示
                    const imageUrl = `/uploads/${material.url}`;
                    html += `
                        <div class="image-container" style="text-align: center; padding: 20px; background: white;">
                            <img src="${imageUrl}" 
                                 alt="${material.name}" 
                                 style="max-width: 100%; max-height: 500px; border-radius: 5px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);"
                                 onload="console.log('Image loaded:', '${material.name}')"
                                 onerror="console.error('Image load error:', '${material.name}')">
                        </div>
                    `;
                } else if (material.contentType && material.contentType.includes('text')) {
                    // 文本文件显示内容
                    html += `
                        <div class="text-container" style="background: #e8f5e9; padding: 30px; border-radius: 5px; text-align: center; border-left: 4px solid #4caf50;">
                            <i class="fas fa-file-alt" style="font-size: 48px; color: #4caf50; margin-bottom: 15px;"></i>
                            <h4 style="margin: 10px 0; color: #388e3c;">文本课件</h4>
                            <p style="margin: 0; color: #666;">${material.name}</p>
                        </div>
                    `;
                } else {
                    // 其他文件类型显示信息
                    html += `
                        <div class="file-info" style="background: #fff3e0; padding: 30px; border-radius: 5px; text-align: center; border-left: 4px solid #ff9800;">
                            <i class="fas ${fileIcon}" style="font-size: 48px; color: #ff9800; margin-bottom: 15px;"></i>
                            <h4 style="margin: 10px 0; color: #f57c00;">课件文件</h4>
                            <p style="margin: 0; color: #666;">${material.name}</p>
                            <p style="margin: 10px 0 0 0; font-size: 14px; color: #999;">文件类型: ${material.contentType || '未知'}</p>
                        </div>
                    `;
                }
                
                html += '</div>'; // 结束 material-section
            });
            
            materialContent.innerHTML = html;
        }

        // 根据文件类型获取图标
        function getFileIcon(contentType) {
            if (!contentType) return 'fa-file';
            
            if (contentType.includes('pdf')) return 'fa-file-pdf';
            if (contentType.includes('word') || contentType.includes('document')) return 'fa-file-word';
            if (contentType.includes('powerpoint') || contentType.includes('presentation')) return 'fa-file-powerpoint';
            if (contentType.includes('text')) return 'fa-file-alt';
            if (contentType.includes('image')) return 'fa-file-image';
            if (contentType.includes('video')) return 'fa-file-video';
            if (contentType.includes('audio')) return 'fa-file-audio';
            
            return 'fa-file';
        }

        // 章节点击事件
        chapterItems.forEach(item => {
            item.addEventListener('click', function() {
                const chapterId = parseInt(this.getAttribute('data-chapter'));
                switchChapter(chapterId);
            });
        });

        // 上一章按钮
        prevBtn.addEventListener('click', function() {
            if (currentChapter === null) return;
            
            const currentIndex = chapters.findIndex(ch => ch.id === currentChapter);
            if (currentIndex > 0) {
                switchChapter(chapters[currentIndex - 1].id);
            }
        });

        // 下一章按钮
        nextBtn.addEventListener('click', function() {
            if (currentChapter === null) return;
            
            const currentIndex = chapters.findIndex(ch => ch.id === currentChapter);
            if (currentIndex < chapters.length - 1) {
                switchChapter(chapters[currentIndex + 1].id);
            }
        });

        // 完成章节按钮
        completeBtn.addEventListener('click', function() {
            if (currentChapter === null) return;
            
            const currentItem = document.querySelector(`.chapter-item[data-chapter="${currentChapter}"]`);

            if (!currentItem.classList.contains('completed')) {
                // 禁用按钮防止重复点击
                completeBtn.disabled = true;
                completeBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 提交中...';
                
                // 调用后端API标记章节为已完成
                const formData = new FormData();
                formData.append('courseId', course.id);
                formData.append('chapterId', currentChapter);
                
                fetch('/student/chapter/complete', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.text())
                .then(result => {
                    if (result === 'ok') {
                        // 重新检查章节完成状态以确保同步
                        checkChapterCompletionStatus(currentChapter);
                        alert('章节已完成！');
                    } else {
                        alert('标记完成失败：' + result);
                        // 恢复按钮状态
                        completeBtn.disabled = false;
                        completeBtn.innerHTML = '<i class="fas fa-check"></i> 标记为已完成';
                        completeBtn.style.backgroundColor = '#28a745';
                    }
                })
                .catch(error => {
                    console.error('完成章节失败:', error);
                    alert('完成章节失败：' + error.message);
                    // 恢复按钮状态
                    completeBtn.disabled = false;
                    completeBtn.innerHTML = '<i class="fas fa-check"></i> 标记为已完成';
                    completeBtn.style.backgroundColor = '#28a745';
                });
            }
        });

        // 更新进度条
        function updateProgress() {
            const completedChapters = document.querySelectorAll('.chapter-item.completed').length;
            const totalChapters = chapters.length;
            const progressPercentage = totalChapters > 0 ? (completedChapters / totalChapters) * 100 : 0;

            // 更新进度条宽度
            document.getElementById('progress-bar').style.width = `${progressPercentage}%`;

            // 更新进度文本
            document.getElementById('progress-percentage').textContent = `${Math.round(progressPercentage)}%`;
        }



        // 初始化 - 如果有章节，默认选择第一个
        if (chapters.length > 0) {
            switchChapter(chapters[0].id);
        }
        updateNavButtons();
    });
</script>
</body>
</html>